{% extends "layout.html" %}

{% block title %}
Tools
{% endblock %}

{% block main %}
<style>
  .center {
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;
    flex-wrap: wrap;
  }
  .textarea-container {
    width: 80%;
    margin-top: 20px;
  }
  textarea {
    width: 100%;
    height: 200px;
  }
  button {
    margin-top: 10px;
  }
</style>

<div class="center">
  <h1>Toggle Values</h1>
  <div class="textarea-container">
    <textarea id="toggleValuesBox" placeholder='Paste new values or retrieve current...'></textarea>
    <button type="button" id="retrieveButton">Retrieve Toggle Values</button>
    <button type="button" id="submitButton">Submit New Values</button>
  </div>
</div>

<script>
  const toggleValuesBox = document.getElementById('toggleValuesBox');
  const retrieveButton = document.getElementById('retrieveButton');
  const submitButton = document.getElementById('submitButton');

  retrieveButton.addEventListener('click', function() {
    fetch('/get_toggle_values')
      .then(response => response.json())
      .then(data => {
        toggleValuesBox.value = JSON.stringify(data, null, 2);
      })
      .catch(error => console.error('Error fetching toggle values:', error));
  });

  submitButton.addEventListener('click', function() {
    let inputData;
    try {
      inputData = JSON.parse(toggleValuesBox.value);
    } catch (error) {
      alert('Invalid JSON format');
      console.error('Error parsing JSON input:', error);
      return;
    }

    fetch('/store_toggle_values', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(inputData),
    })
    .then(response => response.json().then(data => ({ status: response.status, body: data })))
    .then(result => {
      if (result.status === 200) {
        alert('Values stored successfully.');
      } else {
        alert('Error storing values: ' + result.body.error);
      }
    })
    .catch(error => console.error('Error storing toggle values:', error));
  });
</script>
{% endblock %}
